package com.android.cattlefarm.db;

import android.content.Context;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * Created by Huang on 2015/7/4.
 */
public class DBBaseHelper extends SQLiteOpenHelper {

	public DBBaseHelper(Context context) {
		super(context, "CATTLE_FARM.db", null, getVersionCode(context));
	}

	private static DBBaseHelper helper = null;

	public synchronized static DBBaseHelper getInstance(Context context) {
		if (helper == null) {
			DBBaseHelper temp = new DBBaseHelper(context);
			helper = temp;
		}
		return helper;
	}

	private static int getVersionCode(Context context) {
		int versionCode = 1;
		try {
			versionCode = context.getPackageManager().getPackageInfo(
					"com.android.cattlefarm", 0).versionCode;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return versionCode;
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		// 创建导入表
		StringBuffer importStr = new StringBuffer();
		importStr.append("create table if not exists "+ImportDB.IMPORT_TABLE+"(");
		importStr.append("_id integer primary key autoincrement,");
		importStr.append(ImportDB.COW_NUM+" text,");
		importStr.append(ImportDB.COW_FARM_NUM+" text,");
		importStr.append(ImportDB.COW_FARM_NAME+" text,");
		importStr.append(ImportDB.BIRTHDAY+" text,");
		importStr.append(ImportDB.TYRE+" text,");
		importStr.append(ImportDB.PRODUCTION_TIME+" text,");
		importStr.append(ImportDB.FATHER+" text,");
		importStr.append(ImportDB.MOTHER+" text,");
		importStr.append(ImportDB.GRANDFATER +" text);");

		db.execSQL(importStr.toString());

		// 创建导出表
		StringBuffer exportStr = new StringBuffer();
		exportStr.append("create table if not exists "+AddDB.ADD_TABLE+"(");
		exportStr.append("_id integer primary key autoincrement,");
		exportStr.append(ImportDB.COW_NUM+" text,");
		exportStr.append(ImportDB.COW_FARM_NUM+" text,");
		exportStr.append(ImportDB.COW_FARM_NAME+" text,");
		exportStr.append(ImportDB.BIRTHDAY+" text,");
		exportStr.append(ImportDB.TYRE+" text,");
		exportStr.append(ImportDB.PRODUCTION_TIME+" text,");
		exportStr.append(ImportDB.FATHER+" text,");
		exportStr.append(ImportDB.MOTHER+" text,");
		exportStr.append(ImportDB.GRANDFATER+" text,");
		exportStr.append(AddDB.COLUMN_VALUE+" text,");
		exportStr.append(AddDB.AVEGARE+" float,");
		exportStr.append(AddDB.TIQURONGLIANG+" float,");
		exportStr.append(AddDB.KAOBU+" float,");
		exportStr.append(AddDB.ZHITI+" float,");
		exportStr.append(AddDB.QIANRUFANG+" float,");
		exportStr.append(AddDB.HOURUFANG+" float,");
		exportStr.append(AddDB.XITONG+" float,");
		exportStr.append(AddDB.TEZHENG+" float);");

		db.execSQL(exportStr.toString());
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		onCreate(db);
	}

}
